﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Palsta.Core
{
    public class XslWhen : XslElement
    {
        /*
         * Constructors
         */ 
        public XslWhen(XmlNode xslNode)
            : base(xslNode)
        {
             _jsFunctionName = _functionPrefix + "when";
        }

        /*
         * Overrides
         */
        public override String GetFunctionDeclareScript()
        {
            String xslExpression = _xmlNode.Attributes["test"].Value;
            BuildEventObserver(xslExpression);
            String jsExpression = ExpressionParser.ConvertToJSExpression(xslExpression);
            String result = "function " + _jsFunctionName + "_" + _index.ToString() + "() { \r\n";
            result += "if (" + jsExpression + ")\r\n";
            result += "{\r\nvar result = '';";
            foreach (XslElement node in _xslChildNodes)
            {
                result += "\r\nresult += " + node.GetFunctionCallingScript();
            }
            result += "\r\nreturn result;\r\n}\r\n";
            result += "return false;\r\n}\r\n";
            return result;
        }
		
        /*
         * New methods
         */

        protected virtual void BuildEventObserver(String Expression)
        {
            IList<String> listenIds = ExpressionParser.LisentList(Expression);
            XslElement reactNode = GetEventReactParentNode();
            if (reactNode == null)
            {
                reactNode = GetEventReactChildNode();
                if (reactNode != null)
                {
                    reactNode = this;
                }
            }
            if (reactNode == null) return;
            String eventName = "onchange";
            String callback = reactNode.JSFunctionName + "_" + reactNode.NodeIndex;
            foreach (String id in listenIds)
            {
                EventObserver.AddObserver(new EventObserver(eventName, id, callback));
            }
        }
    }
}
